package org.invigorare.auctions.comm;

import java.util.*;

import org.invigorare.auctions.R;

import android.content.Context;

public class InboundSyncResult {

	final List<DbSyncResult> dbResults;
	
	public enum InboundStatus {
		NORMAL,
		INVALID_EMPLOYEE_ID,
		JSON_PARSE_ERROR,
		UNRESOLVED_HOST,
		WEBSERVICE_OTHER_ERROR,
		NO_CONNECTIONS
	}
	
	final InboundStatus status;
	final Object extraInfo;
	final boolean settingsSynced;
	
	public InboundSyncResult(InboundStatus status, Object extraInfo, boolean settingsSynced, DbSyncResult ... dbResults) {
		this.status = status;
		this.extraInfo = extraInfo;
		this.settingsSynced = settingsSynced;
		
		this.dbResults = new ArrayList<DbSyncResult>(dbResults.length);
		for (DbSyncResult r : dbResults) {
			this.dbResults.add(r);
		}
	}
	
	public List<DbSyncResult> getDbResults() {
		return dbResults;
	}
	
	public InboundStatus getOverallStatus() {
		return status;
	}
	
	public boolean settingsSuccessful() {
		return settingsSynced;
	}
	
	/**
	 * Returns a string summary of this Result object, suitable for display.
	 * @param context the Application Context from which human-readable error strings can be fetched (may be null) 
	 * @return
	 */
	public String toString(Context context) {
		StringBuilder sb = new StringBuilder();
		
		/* Normal status: toString each individual db's result object */
		if (status == InboundStatus.NORMAL) {
			for (DbSyncResult r : dbResults) {
				sb.append(r.toString());
				sb.append("\n");
			}
			//sb.replace(sb.length()-1, sb.length(), ""); // remove last (extra) newline character
			
			/* Settings Successfully synced */
			if (context != null) {
				sb.append(context.getString(settingsSynced ? R.string.sync_settings_success : R.string.sync_settings_failure));
			} else {
				sb.append(settingsSynced ? "Synced Settings from server." : "Error occurred while storing Settings.");
			}
		}
		
		/* Error status: fetch the appropriate error string */
		else {
			if (context != null) {
				if (status == InboundStatus.INVALID_EMPLOYEE_ID) {
					sb.append(context.getString(R.string.sync_error_invalidEmployeeId));
				} else if (status == InboundStatus.JSON_PARSE_ERROR) {
					sb.append(context.getString(R.string.sync_error_inboundParseError));
				} else if (status == InboundStatus.NO_CONNECTIONS) {
					sb.append(context.getString(R.string.sync_error_noConnections));
				} else if (status == InboundStatus.UNRESOLVED_HOST) {
					sb.append(context.getString(R.string.sync_error_unresolvedHost));
				} else if (status == InboundStatus.WEBSERVICE_OTHER_ERROR) {
					sb.append(context.getString(R.string.sync_error_webserviceLayerError));
				} 
			} else {
				sb.append("Sync Error: ");
				sb.append(status.toString());
			}
			
		}
		
		return sb.toString();
	}
	
	public String toString() {
		return toString(null);
	}
}
